﻿using System;
using SFML.Audio;
using SFML.Graphics;
using SFML.Window;

namespace SFMLPlatformerEngine {

	class Player {

		public bool isLife = true;
		public bool onGround;
		public Sprite sprite;
		public FloatRect rect;
		public float dx, dy;
		public float currentFrame;
		public float frameCount;
		public Direction direction;
		public Map map;

		public Player(Texture texture, Map map) {
			sprite = new Sprite(texture);
			rect = new FloatRect(100, 100, 20, 40);
			direction = Direction.Right;
			this.map = map;
		}

		public void Update(float time) {
			rect.Left += dx * time;

			Collision(Direction.Horizontal);

			if(!onGround)
				dy = dy + 0.0006f * time;

			rect.Top += dy * time;
			onGround = false;

			Collision(Direction.Vertical);

			frameCount = dx != 0 & dy == 0 ? 6 : 4;

			currentFrame += 0.006f * time;
			if(currentFrame > frameCount)
				currentFrame -= frameCount;

			if(dx > 0)
				sprite.TextureRect = new IntRect(40 * (int)currentFrame, 50, 40, 50);
			if(dx < 0)
				sprite.TextureRect = new IntRect(40 * (int)currentFrame + 40, 50, -40, 50);
			if(dx == 0)
				sprite.TextureRect = direction == Direction.Right ? new IntRect(40 * (int)currentFrame, 0, 40, 50) : new IntRect(40 * (int)currentFrame + 40, 0, -40, 50);
			if(dy != 0)
				sprite.TextureRect = direction == Direction.Right ? new IntRect(40 * (int)currentFrame, 100, 40, 50) : new IntRect(40 * (int)currentFrame + 40, 100, -40, 50);

			sprite.Position = new Vector2f(rect.Left - 10 - map.offsetX, rect.Top - 10 - map.offsetY);

			dx = 0;
		}

		void Collision(Direction dir) {
			for(int i = (int)rect.Top / 32; i < (rect.Top + rect.Height) / 32; i++)
				for(int j = (int)rect.Left / 32; j < (rect.Left + rect.Width) / 32; j++) {
					try {
						if(map.tileMap[i][j] == 'W') {
							if((dx > 0) && (dir == Direction.Horizontal))
								rect.Left = j * 32 - rect.Width;
							if((dx < 0) && (dir == Direction.Horizontal))
								rect.Left = j * 32 + 32;

							if((dy > 0) && (dir == Direction.Vertical)) {
								rect.Top = i * 32 - rect.Height;
								dy = 0;
								onGround = true;
							}
							if((dy < 0) && (dir == Direction.Vertical)) {
								rect.Top = i * 32 + 32;
								dy = 0;
							}
						}
						if(map.tileMap[i][j] == 'C') {
							map.tileMap[i] = map.tileMap[i].Remove(j, 1).Insert(j, " ");
							new Sound(new SoundBuffer("res/coin.wav")).Play();
						}
						if(map.tileMap[i][j] == 'D') {
							map.tileMap[i] = map.tileMap[i].Remove(j, 1).Insert(j, " ");
							new Sound(new SoundBuffer("res/tada.wav")).Play();
						}
					} catch {
						Console.WriteLine("Выход из массива.");
					}
				}
		}
	}
}
